package com.kt.game1

/**
 * Kotlin 贪吃蛇游戏示例
 */

fun main() {
    val game = SnakeGame()
    game.start()
}

class SnakeGame {
    private val width = 20
    private val height = 10
    private val board = Array(height) { CharArray(width) }
    private var snake = mutableListOf(Pair(5, 5))
    private var direction = 'R'
    private var food = generateFood()
    private var gameOver = false
    private var score = 0

    fun start() {
        println("欢迎来到贪吃蛇游戏！")
        println("使用 W、A、S、D 控制蛇的方向")
        println("按 Q 退出游戏")

        while (!gameOver) {
            clearScreen()
            drawBoard()
            handleInput()
            updateGame()
            Thread.sleep(200)
        }

        println("游戏结束！你的分数是 $score")
    }

    private fun clearScreen() {
        println("\n".repeat(30))
    }

    private fun drawBoard() {
        for (i in 0 until height) {
            for (j in 0 until width) {
                if (i == 0 || i == height - 1 || j == 0 || j == width - 1) {
                    print("#")
                } else {
                    print(' ')
                }
            }
            println()
        }

        for ((x, y) in snake) {
            board[y][x] = 'O'
        }

        board[food.second][food.first] = 'X'

        for (row in board) {
            println(row.joinToString(""))
        }
    }

    private fun handleInput() {
        val input = readLine()?.firstOrNull() ?: return

        when (input) {
            'W', 'w' -> if (direction != 'S') direction = 'U'
            'A', 'a' -> if (direction != 'D') direction = 'L'
            'S', 's' -> if (direction != 'U') direction = 'D'
            'D', 'd' -> if (direction != 'L') direction = 'R'
            'Q', 'q' -> gameOver = true
        }
    }

    private fun updateGame() {
        val head = snake.first()
        var newHead = head

        when (direction) {
            'U' -> newHead = Pair(head.first, head.second - 1)
            'D' -> newHead = Pair(head.first, head.second + 1)
            'L' -> newHead = Pair(head.first - 1, head.second)
            'R' -> newHead = Pair(head.first + 1, head.second)
        }

        if (newHead.first < 1 || newHead.first >= width - 1 || newHead.second < 1 || newHead.second >= height - 1) {
            gameOver = true
            return
        }

        if (snake.contains(newHead)) {
            gameOver = true
            return
        }

        snake.add(0, newHead)

        if (newHead == food) {
            score++
            food = generateFood()
        } else {
            snake.removeAt(snake.size-1)
        }
    }

    private fun generateFood(): Pair<Int, Int> {
        var food: Pair<Int, Int>
        do {
            food = Pair((1 until width - 1).random(), (1 until height - 1).random())
        } while (snake.contains(food))

        return food
    }
}